package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.user.IUserRegisterService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.UUID;

/**
 * @author pengyehua
 * @date 2020/12/19 21:43
 */
@Slf4j
@Service(interfaceClass = IUserRegisterService.class)
@Component
public class UserRegisterServiceImpl implements IUserRegisterService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    JavaMailSender javaMailSender;

    @Override
    public UserRegisterResponse register(UserRegisterRequest request) {
        UserRegisterResponse response = new UserRegisterResponse();
        //参数判空
        request.requestCheck();
        //判断用户名是否重复
        if (validUsernameRepeat(request.getUserName())) {
            response.setCode(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode());
            response.setMsg(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
            return response;
        }

        //判断邮箱是否重复
        if (validEmailRepeat(request.getEmail())) {
            response.setCode(SysRetCodeConstants.EMAIL_ALREADY_EXISTS.getCode());
            response.setMsg(SysRetCodeConstants.EMAIL_ALREADY_EXISTS.getMessage());
            return response;
        }
        //1. 向⽤用户表中插⼊入⼀一条记录
        Member member = new Member();
        member.setUsername(request.getUserName());
        //使用MD5加密
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(request.getUserPwd().getBytes());
        member.setPassword(md5DigestAsHex);
        member.setEmail(request.getEmail());
        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setState(1);
        member.setIsVerified("N");
        int insert = memberMapper.insert(member);
        //插入用户表失败
        if (insert != 1) {
            response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
            return response;
        }
        //2. 向⽤用户验证表中插⼊一条记录
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(request.getUserName());
        userVerify.setRegisterDate(new Date());
        //生成uuid
        String key = request.getUserName() + request.getUserPwd() + UUID.randomUUID().toString();
        String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
        userVerify.setUuid(uuid);
        userVerify.setIsVerify("N");
        userVerify.setIsExpire("N");
        int row = userVerifyMapper.insert(userVerify);
        //插入用户验证表失败
        if (row != 1) {
            response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
            return response;
        }
        //3. 新起一个线程，发送⽤用户激活邮件
        new Thread(new Runnable() {
            @Override
            public void run() {
                sendMail(uuid, request);
                log.info("邮件发送成功");
            }
        }).start();

        //打印日志
        log.info("用户注册成功，注册信息：{}", JSON.toJSONString(request));
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }

    /**
     * 判断邮箱是否重复
     *
     * @param email
     */
    private boolean validEmailRepeat(String email) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("email", email);
        int count = memberMapper.selectCountByExample(example);
        if (count > 0) {
//            throw new ValidateException(SysRetCodeConstants.EMAIL_ALREADY_EXISTS.getCode(),
//                    SysRetCodeConstants.EMAIL_ALREADY_EXISTS.getMessage());
            return true;
        }
        return false;
    }

    /**
     * 发送用户激活邮件
     *
     * @param uuid
     * @param request
     */
    private void sendMail(String uuid, UserRegisterRequest request) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("xiaopeng__1006@163.com");
        message.setTo(request.getEmail());
        message.setSubject("csMall激活");
        StringBuffer buffer = new StringBuffer();
        buffer.append("http://localhost:8080/user/verify?uid=").
                append(uuid).
                append("&username=").
                append(request.getUserName());
        message.setText("点击该链接激活账户: " + buffer);
        javaMailSender.send(message);
    }

    /**
     * 判断用户名是否重复
     *
     * @param userName
     */
    private boolean validUsernameRepeat(String userName) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", userName);
        int count = memberMapper.selectCountByExample(example);
        if (count > 0) {
//            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(),
//                    SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
            return true;
        }
        return false;
    }
}
